package com.example.village.controller;

import com.example.common.utils.R;
import com.example.village.entity.UserEntity;
import com.example.village.entityVO.UserRegisterVO;
import com.example.village.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Api(tags = "登录接口")
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    @ApiOperation("登录")
    @RequestMapping(value = "/login", method = POST)
    public R login(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        if (username == null || password == null){
            return R.error("账号密码不能为空！");
        }
        UserEntity user = userService.login(username, password);
        if (user != null) {
            return R.ok().put("user", user);
        }
        return R.error("登录失败！");
    }

    @ApiOperation("注册")
    @RequestMapping(value = "/register", method = POST)
    public R register(@RequestBody UserRegisterVO user) {
        if (userService.register(user)) {
            return R.ok("注册成功！");
        }
        return R.error("注册失败！");
    }
}
